<?php
class ModuleSnsShinezone extends ModuleSns
{

    private static $apiUrl = null;

    private static $apiVersion ='2.0';
    /**
     * @var int $platformId
     */
    protected $platformId;

    /**
     * @see ModuleSns::__construct()
     */
    public function __construct($userId, $platform, $configs)
    {
        /**
         * array(
         *     'appId' => array('key' => 'appId', 'value' => ...),
         *     'appSecret' => array('key' => 'appSecret', 'value' => ...),
         *     'appToken' => array('key' => 'appToken', 'value' => ...),
         *     'payToken' => array('key' => 'payToken', 'value' => ...),
         * )
         *
         * @var array $configs
         */
        parent::__construct($userId, $platform, $configs);
        if (isset($_REQUEST['session_id']) && isset($_REQUEST['sz_id'])) {
            if (is_null(self::$apiUrl)) {
                $this->updateVersion();
            }
            $this->checkSession($_REQUEST['session_id'], $_REQUEST['sz_id']);
        }
    }

    /**
     * @see ModuleSns::createJsEmbededCode()
     */
    public function createJsEmbeddedCode()
    {
        return '';
    }

    /**
     * @see ModuleSns::getPfToken()
     */
    public function getPfToken()
    {
        return SzParam::getReqParam('session_id');
    }

    /**
     * @see ModuleSns::getPfSignature()
     */
    public function getPfSignature()
    {
        return null;
    }

    /**
     * @see ModuleSns::initializeOnIndex()
     */
    public function initializeOnIndex()
    {
        return array($this->userId, ModuleSnsConst::PFSZ);
    }

    /**
     * 读取玩家信息
     * @param string $platformId
     * @return array
     */
    public function getUserInfo($platformId)
    {
        if (is_null(self::$apiUrl)) {
            $this->updateVersion();
        }

        $params = array(
            'cp_id' => $this->configs['appId']['value'],
            'timestamp' => time(),
            'sz_ids' => "$platformId",
            'cp_key' => $this->configs['appSecret']['value']
        );
        $signKeys = array('cp_id', 'timestamp', 'cp_key');

        $result = $this->sendRequest('user/get_users_batch', $params, $signKeys);

        if (SzUtility::checkArrayKey('code', $result) && $result['code'] == 0) {
            return $result['users'];
        } else {
            return array();
        }
    }

    /**
     * 初始化接口
     *
     * @return array
     * @throws SzException
     * @throws SzException
     */
    public function updateVersion()
    {
        $gameSetting = $env = SzConfig::get()->loadAppConfig('app');
        $params = array(
            'cp_id' => $this->configs['appId']['value'],
            'game_id' => $gameSetting['GAME_ID'],
            'timestamp' => time(),
            'cp_key' => $this->configs['appSecret']['value']
        );
        $signKeys = array('cp_id', 'timestamp', 'cp_key');

        if ($gameSetting['ENV'] == 'DEV') {
            self::$apiUrl = 'https://api-test.shinezone.com/';
        } else {
            self::$apiUrl = 'https://api.shinezone.com/';
        }
        $result = $this->sendRequest('user/update_version', $params, $signKeys);

        if (isset($result['data']['ApiServer'])) {
            self::$apiUrl = $result['data']['ApiServer'];
            self::$apiVersion = $result['data']['Version'];
        }
    }
    /**
     * 效验用户登入的会话id
     *
     * @param $sessionId
     * @param $szId
     * @return array
     * @throws SzException
     * @throws SzException
     */
    public function checkSession($sessionId, $szId)
    {
        $params = array(
            'cp_id' => $this->configs['appId']['value'],
            'session_id' => $sessionId,
            'timestamp' => time(),
            'cp_key' => $this->configs['appSecret']['value']
        );
        $signKeys = array('cp_id', 'session_id', 'timestamp', 'cp_key');

        $result = $this->sendRequest('user/check_session', $params, $signKeys);
        if ($result['szid'] != $szId) {
            throw new SzException(30205, json_encode($result), ModuleSnsConst::MODULE_NAME);
        }
        return $result;
    }

    /**
     * 发送请求, 处理错误
     * @param string $controller
     * @param array $params default array
     * @param array $signKeys default array, 参与计算sign的参数列表
     * @throws Exception
     * @throws SzException
     * @return array
     */
    private function sendRequest($controller, $params = array(), $signKeys = array())
    {
        // 生成实际的api地址
        $apiUrl = sprintf('%s%s/%s/', self::$apiUrl, self::$apiVersion, $controller);
        // 根据不同接口的签名参数, 生成签名
        if (is_array($signKeys) && !empty($signKeys)) {
            $params['sign'] = $this->makeSign($params, $signKeys);
        }
        // post请求给平台, 拿到response
        SzLogger::get()->debug('$apiUrl:' . $apiUrl);
        SzLogger::get()->debug('$params:' . var_export($params, true));
        $result = SzUtility::postHttpRequest($apiUrl, $params);
        $result = json_decode($result, true);
        // 判断请求是否正确
        if ($result['code'] != 0) {
            throw new SzException(30204, array(json_encode($result), json_encode($params)), ModuleSnsConst::MODULE_NAME);
        }
        SzLogger::get()->debug('**********************');
        return $result;
    }

    /**
     * 生成签名
     *
     * @param array $params
     * @param array $signKeys
     * @return string
     */
    public function makeSign($params, $signKeys)
    {
        $signStr = '';
        foreach ($signKeys as $key) {
            $signStr .= $params[$key];
        }
        return md5($signStr);
    }

    /**
     * @see ModuleSns::getPfFriends()
     */
    protected function getPfFriends($userId)
    {
        return array();
    }

    /**
     * @see ModuleSns::preparePfApiEnv()
     */
    protected function preparePfApiEnv()
    {
    }

    /**
     * @see ModuleSns::checkResult()
     */
    protected function checkResult($result)
    {
    }

    /**
     * 读取玩家信息
     *
     * @param array $platformIds real shinezoneId
     * @return array
     */
    public function getUserInfos($platformIds)
    {
        if (is_null(self::$apiUrl)) {
            $this->updateVersion();
        }

        $result = array();
        $ids = '';
        foreach ($platformIds as $platformId) {
            $ids .= "$platformId,";
        }
        $ids = substr($ids, 0, -1);
        $params = array(
            'cp_id' => $this->configs['appId']['value'],
            'timestamp' => time(),
            'sz_ids' => $ids,
            'cp_key' => $this->configs['appSecret']['value']
        );
        $signKeys = array('cp_id', 'timestamp', 'cp_key');

        $result = $this->sendRequest('user/get_users_batch', $params, $signKeys);
        if (SzUtility::checkArrayKey('code', $result) && $result['code'] == 0) {
            return $result['users'];
        } else {
            return array();
        }
    }
}